<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Admin\BaseController;
use App\Models\Admin\Permission;
use Illuminate\Http\Request;
use DB;

class PermissionController extends BaseController
{
    public function toCreate()
    {
        $permission = new permission();
        return view('admin.auth.permission.permission',compact('permission'));
    }
    public function toEdit(Permission $permission)
    {
        return view('admin.auth.permission.permission', compact('permission'));
    }

    public function save(Request $request)
    {
        if($request->input('id')){
            $cnt1 = Permission::where('name', $request->input('name'))->where('id', '!=', $request->input('id'))->count();
            if($cnt1){
                return $this->error('标签已被注册');
            }
            $permission = Permission::find($request->input('id'));
            $permission->name = $request->input('name');
            $permission->display_name = $request->input('display_name');
            $permission->url = $request->input('url');
            $permission->description = $request->input('description');
        }else{
            $cnt1 = Permission::where('name', $request->input('name'))->count();
            if($cnt1){
                return $this->error('标签已被注册');
            }
            $permission = new Permission();
            $permission->name = $request->input('name');
            $permission->display_name = $request->input('display_name');
            $permission->url = $request->input('url');
            $permission->description = $request->input('description');
        }
        $ret = $permission->save();

        if($ret){
            return $this->success('提交成功', route('admin-permissions'));
        }else{
            return $this->error();
        }
    }

    public function permissions()
    {
        $list = Permission::all();
        return view('admin.auth.permission.permissions', compact('list'));
    }

    public function select(Request $request)
    {
        $role_id = $request->input('role_id');
        $role_permissions = DB::select('select permission_id from permission_role where role_id = '.$role_id);
        $rps = array();
        foreach ($role_permissions as $rp){
            $rps[] = $rp->permission_id;
        }
        $permissions = DB::select('select * from permissions');
        $list = array();
        foreach ($permissions as $p){
            $p->checked = in_array($p->id, $rps);
            $list[] = $p;
        }
        return view('admin.auth.permission.select', compact('list','role_id'));
    }

    public function delete(Permission $permission){
        $ret = $permission->delete();
        if($ret){
            return $this->success('删除成功');
        }else{
            return $this->error();
        }
    }
}
